package com.elite.groovy.callback

import com.elite.groovy.util.EliteBean
import com.elite.groovy.util.Util
import com.elite.groovy.kh.KHUtil
import net.sf.json.JSONObject
import org.apache.commons.logging.Log
import org.apache.commons.logging.LogFactory
import org.springframework.jdbc.core.JdbcTemplate
import com.sun.org.apache.xml.internal.security.utils.Base64;
import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

/**
 *
 * @Title: apiPjRequst*
 * @Description:品检系统接口调用 *
 * @remak ：品检系统调用*
 * @author: TH*
 * @date 2024-03-26 11:11:00
 *
 */
public  class apiPjRequst  implements ServiceBackInvoke{
    private static String defaultCharset = "UTF-8";
    private static final Log log = LogFactory.getLog(apiPjRequst.class);
    @Override
 public    String doCallBack(EliteBean eliteBean, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json;charset=UTF-8");

        JSONObject backjson = new JSONObject();

        long starttime = System.currentTimeMillis();
        //获取接口调用方式及参数
        String GetMethod = httpServletRequest.getMethod();
        log.debug("[GetMethod]:" + GetMethod);

        String inData = "";
        if (GetMethod.equals("GET")) {
            inData = httpServletRequest.getParameter("data");
            log.debug("[原始Get请求参数：]" + inData);
        } else {
            InputStreamReader reader = new InputStreamReader(httpServletRequest.getInputStream(), "UTF-8");
            BufferedReader iny = new BufferedReader(reader);
            String line;
            while ((line = iny.readLine()) != null) {
                inData += line;
            }
            log.debug("[原始Post请求参数：]" + inData);
        }


        if (KHUtil.isNull(inData)) {
            log.error("请求接口入参为空-无法完成操作！");
            backjson.put("code", '-1');
            backjson.put("msg", "请求接口入参为空-无法完成操作！")
            return backjson;
        }
        log.debug("apiPjRequst-version:20240411")
        try {
            JSONObject jsonObject = JSONObject.fromObject(inData);

            String id = GetJV(jsonObject, "id");//id
            String operationStartTime = GetJV(jsonObject, "operationStartTime");//开始时间
            String operationEndTime = GetJV(jsonObject, "operationEndTime"); //结束时间
            String type = GetJV(jsonObject, "type"); //业务类型  yzg: 已整改   wxzg:无需整改
            String checkResult = GetJV(jsonObject, "checkResult"); //状态，保持之前接口的参数，之前的接口是传什么这次也传什么
            String userCode=GetJV(jsonObject,"userCode");//用户编码
            String userName=GetJV(jsonObject,"userName");//用户名



            //已整改
            String rectificationreason=GetJV(jsonObject,"rectificationreason");//code值
            String yesdesc=GetJV(jsonObject,"yesdesc");//选择其他的，填充值


            //无需整改
            String norectificationreason=GetJV(jsonObject,"norectificationreason");//code值
            String nodesc=GetJV(jsonObject,"nodesc");//选择其他的，填充值


            //设置请求表头
            Map<String, String> TokenParams = new HashMap<String, String>();
            TokenParams.put("Content-Type", "application/json");
            TokenParams.put("userCode", Base64.encode(userCode.toString().getBytes(defaultCharset)));
            TokenParams.put("userName", Base64.encode(userName.toString().getBytes(defaultCharset)));



            List PJURLLIST=eliteBean.chaxun_sql("SELECT WEBSERVICEURL FROM sysc_interface WHERE WEBTYPE='PJ-URL'","dataSource");
            String PJURL = PJURLLIST.get(0).get("WEBSERVICEURL");


             if (type.equals("yzg")){

                 //设置extModel json
                 JSONObject  extModel  =new JSONObject();
                 extModel.put("dataType",0);
                 extModel.put("type",rectificationreason);
                 extModel.put("opinion",yesdesc);


                 //设置请求外部头
                 JSONObject  requstjson  =new JSONObject();
                 requstjson.put("id",id);
                 requstjson.put("operationStartTime",operationStartTime);
                 requstjson.put("operationEndTime",operationEndTime);
                 requstjson.put("checkResult",checkResult);
                 requstjson.put("extModel",extModel);


                 log.debug("调用品检标记无需正噶整改接口请求报文："+requstjson.toString());
                 String rponsebody = Util.doHttpPostUseHead(PJURL.toString()+"/outsideSystem/inspection/rectified", requstjson.toString(), "UTF-8", 20000, 0, TokenParams);

                 JSONObject rponsebodyjson=JSONObject.fromObject(rponsebody);

                 String code=GetJV(rponsebodyjson,"code");
                 String msg=GetJV(rponsebodyjson,"msg");
                 if (code.equals("200")){

                     backjson.put("code", code);
                     backjson.put("msg", msg);

                 }else{

                     log.error("调用品检标记已整改接口失败！");
                     backjson.put("code", code);
                     backjson.put("msg", msg);

                 }

                 String insertsql = '''
                               insert into fcqt_dm_ifc_log_new
                               (id,ifc_no,send_info,return_info,send_time,return_time) 
                               values
                                  (
                                  Sys_Guid(),
                                  'apiPjRequst',
                                  ?,
                                  ?,
                                  sysdate,
                                  sysdate
                                  )
                              ''';

                 jt.update(insertsql, requstjson.toString(),backjson.toString());




             }else if (type.equals("wxzg")){

                 //设置extModel json
                 JSONObject  extModel  =new JSONObject();
                 extModel.put("dataType",1);
                 extModel.put("type",norectificationreason);
                 extModel.put("opinion",nodesc);


                 //设置请求外部头
                 JSONObject  requstjson  =new JSONObject();
                 requstjson.put("id",id);
                 requstjson.put("operationStartTime",operationStartTime);
                 requstjson.put("operationEndTime",operationEndTime);
                 requstjson.put("checkResult",checkResult);
                 requstjson.put("extModel",extModel);


                 log.debug("调用品检标记无需整改接口请求报文："+requstjson.toString());
                 String rponsebody = Util.doHttpPostUseHead(PJURL.toString()+"/outsideSystem/inspection/noRectification", requstjson.toString(), "UTF-8", 20000, 0, TokenParams);

                 JSONObject rponsebodyjson=JSONObject.fromObject(rponsebody);

                 String code=GetJV(rponsebodyjson,"code");
                 String msg=GetJV(rponsebodyjson,"msg");
                 if (code.equals("200")){

                     backjson.put("code", code);
                     backjson.put("msg", msg);

                 }else{

                     log.error("调用品检标记已整改接口失败！");
                     backjson.put("code", code);
                     backjson.put("msg", msg);

                 }
                 String insertsql = '''
                               insert into fcqt_dm_ifc_log_new
                               (id,ifc_no,send_info,return_info,send_time,return_time) 
                               values
                                  (
                                  Sys_Guid(),
                                  'apiPjRequst',
                                  ?,
                                  ?,
                                  sysdate,
                                  sysdate
                                  )
                              ''';

                 jt.update(insertsql, requstjson.toString(),backjson.toString());


             }







        }catch (Exception e) {
            log.error("调用品检接口处理异常", e);
            backjson.put("code", -1);
            backjson.put("msg", "品检调用接口处理异常:" + e.getMessage());

        }


        return backjson;
    }

    public static String GetJV(JSONObject inJson, String getKey) {
        String Rev_Value = null;
        try {
            Rev_Value = inJson.getString(getKey);
            //log.debug("GetJV 获取参数值(String)-" + getKey + ":" + Rev_Value);
        } catch (Exception e) {
            try {
                Rev_Value = String.valueOf(inJson.getInt(getKey));
                //log.debug("GetJV 获取参数值(Integer)-" + getKey + ":" + Rev_Value);
            } catch (Exception e1) {
                Rev_Value = "";
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
            }
        } finally {
            if (Rev_Value == null || Rev_Value.equals("null") || Rev_Value.length() <= 0) {
                //log.debug("GetJV 获取参数值Exception-" + getKey + ":" + Rev_Value);
                Rev_Value = "";
            }
        }
        return Rev_Value;
    }
}
